package com.jsu.hotelmanagement.config;

import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Mo
 * @createTime 2022/11/21 21:11
 * @description 返回允许跨域的响应头
 */

@Order(-9999)
@WebFilter(filterName = "corsFilter", urlPatterns = {"/*"})
@Component
public class FilterConfig implements Filter{
    @Override
    public void init(javax.servlet.FilterConfig filterConfig) throws ServletException {
        System.out.println("++++++++++++++++++++++++++++corsFilter initialized...");
    }

    @Override
    public void destroy() {
        System.out.println("corsFilter initialized...");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String origin = httpServletRequest.getHeader(HttpHeaders.ORIGIN);
        if (origin != null) {
            if (!origin.equals(httpServletResponse.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN))) {
                //  设置允许跨域的源
                httpServletResponse.addHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, origin);
                //  设置给客户端暴露的头文件
                httpServletResponse.addHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, Pragma");
                //  跨域支持的头文件
                httpServletResponse.addHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS,"Origin, token, Content-Length, X-Requested-With , yourHeaderField, Content-Type, Accept, Authorization");
                //  跨域支持的请求方法
                httpServletResponse.addHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET, POST, PUT, OPTIONS, DELETE");
                //  是否允许携带cookie
                httpServletResponse.addHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
                //  预检过期时间
                httpServletResponse.addHeader(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "3600");
            }
        }
        if("OPTIONS".equals(httpServletRequest.getMethod())) {
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            return;
        }
        chain.doFilter(request,response);
    }
}
